#include <stdio.h>

int const MN=50000; //最大堆数;
typedef struct pile_node PNode; 
struct pile_node{
    PNode *next;
    PNode *pre;
    int cnt;
} pnodes[MN+2]; //每堆石子数
PNode *head = NULL; //链表头
int const MS=1e9+7; //最大分数
int n; //实际堆数

PNode *p; //k-1

void rinsert(void) {
    //查找插入点
    PNode *tp = p->pre;
    while(tp->cnt <= p->cnt) {
        tp = tp->pre;
    }
    PNode *next = p->next->next;
    if(tp == p->pre) {
        p->next = next;
        next->pre = p;
    } else { //必须删除p后重新插入
        //删除p
        p->pre->next = next;
        next->pre = p->pre;
        //插入p
        p->pre = tp;
        p->next = tp->next;
        tp->next->pre = p;
        tp->next = p;
    }
    p = tp->pre;
    if(!p || p==&pnodes[0])
        p = pnodes->next;
}
int garsia_wachs(void) {
    int score = 0;
    p = &pnodes[1];
    int size = n;
    while(size-- > 1) { 
        while(p->cnt > p->next->next->cnt) 
            p = p->next;
        //合并
        p->cnt += p->next->cnt;
        score += p->cnt;
        rinsert(); //把p重新插入链表
    }
    return score;
}

int main(void) {
    pnodes[0].pre = NULL;
    pnodes[0].cnt = MS;
    while(true) {
        scanf("%d", &n);
        if(!n) break;
        pnodes[0].next = &pnodes[1];
        int i;
        for(i=1; i<=n; i++) {
            scanf("%d", &pnodes[i].cnt);
            pnodes[i].pre = &pnodes[i-1];
            pnodes[i].next = &pnodes[i+1];
        }
        pnodes[i].next = NULL;
        pnodes[i].pre = &pnodes[n];
        pnodes[i].cnt = MS;
        printf("%d\n", garsia_wachs());
    }
    return 0;
}
